package org.hongqi.common.senpec.base.spring.security.authenticaiton;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hongqi.common.senpec.base.sevlet.Result;
import org.hongqi.common.senpec.base.spring.redis.RedisService;
import org.hongqi.common.senpec.base.spring.security.jwt.JWTService;
import org.hongqi.common.senpec.sys.user.User;
import org.hongqi.common.senpec.sys.user.UserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthenticationServiceImpl implements AuthenticationService {

    private final UserService userService;
    private final JWTService jwtService;
    private final RedisService<String> redisService;
    private final AuthenticationManager authenticationManager;

    @Override
    public Result<User> registerUser(User user) {
        log.info("registerUser is running with {}", user);
        return userService.mySave(user);
    }

    @Override
    public Result<AuthenticationModel> handleAuthenticateSuccess() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.myGetByUsername(username);
        String token = jwtService.generateToken(user);
        redisService.setOne(user.getUsername() + "-token", token);
        AuthenticationModel authenticationModel = AuthenticationModel.builder().username(username).name(user.getName()).id(user.getId()).jobno(user.getJobno()).token(token).build();
        return Result.ok(authenticationModel).msg("登录成功");
    }

    @Override
    public Result<AuthenticationModel> handleAuthenticateFail() {
        return Result.error(AuthenticationModel.builder().build()).msg("登录失败。");
    }

    @Override
    public Result<User> login(User user) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        String token = jwtService.generateToken(user);
        User userSelected = userService.myGetByUsername(user.getUsername());
        userSelected.setToken(token);
        redisService.setOne(user.getUsername() + "-token", token);
        return Result.ok(userSelected.toSafe()).msg("登录成功");
    }

    @Override
    public Result<?> logout(String username) {
        redisService.deleteKey(username + "-token");
        return Result.ok().msg("注销成功");
    }

}
